import 'dart:math';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import 'news.dart';
import 'dart:convert';
import 'newsDetail.dart';

class dynamicPage extends StatefulWidget{
  const dynamicPage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState()=>dynamicPageState();
}

class dynamicPageState extends State<dynamicPage>{
  var page = 1;
  bool hasMore = true;
  List<News> datas = [];
  ScrollController scrollController = new ScrollController();
  @override

  void initState(){
    get();
    _getData();
    scrollController.addListener((){
      if(scrollController.position.pixels>scrollController.position.maxScrollExtent-5){
        page++;
        this._getData();
      }
    });
  }

  // 获取新闻
  void _getData() async {
    final response = await http.get(Uri.parse(
        'http://api.tianapi.com/generalnews/index?key=16624761daf3871b4f2e189788cc2533&num=10&page=${page}'
    ));

    Utf8Decoder decode = Utf8Decoder();
    Map<String, dynamic> result = jsonDecode(decode.convert(response.bodyBytes));
    datas = result['newslist'].map<News>((item) => News.fromJson(item)).toList();

    print('数据${result}');
    print('页数${page}');

    if(datas.length>0){
      setState(() {
        // 关闭加载
        this.hasMore = false;
        save(datas);
      });
    }

  }
  // 保存信息
  save(datas) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    List<String> titil = [];
    List<String> msg = [];
    List<String> ctime = [];
    List<String> description = [];
    List<String> picUrl = [];
    List<String> url = [];
    for(int i = 0; i < 5; i++){
      titil.add(datas[i].title.toString());
      msg.add(datas[i].msg.toString());
      ctime.add(datas[i].ctime.toString());
      description.add(datas[i].description.toString());
      url.add(datas[i].url.toString());
      picUrl.add(datas[i].picUrl.toString());
    }
    prefs.setStringList('titil', titil);
    prefs.setStringList('msg', msg);
    prefs.setStringList('ctime', ctime);
    prefs.setStringList('description', description);
    prefs.setStringList('url', url);
    prefs.setStringList('picUrl', picUrl);
  }
  // 获取信息
  get() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    List<News> newsData =[];
    var titil = prefs.getStringList('titil');
    var msg = prefs.getStringList('msg');
    var ctime = prefs.getStringList('ctime');
    var description = prefs.getStringList('description');
    var url = prefs.getStringList('url');
    var picUrl = prefs.getStringList('picUrl');
    for(int i=0; i< 5;i++){
      News news = News();
      news.title = titil![i];
      news.ctime = ctime![i];
      news.msg = msg![i];
      news.description = description![i];
      news.url = url![i];
      news.picUrl = picUrl![i];
      newsData.add(news);
    }
    // print('urlList${prefs.getStringList('url')}');
    setState(() {
      // 关闭加载
      datas = newsData;
      this.hasMore = false;
    });
  }

// 下拉刷新
  Future<void> onRefresh() async{
    print("下拉刷新");
    // 持续两秒
    await Future.delayed(Duration(milliseconds:2000),(){
      page=1;
      _getData();
    });
    print(this.page);
  }

  // 加载动画
  Widget _getMoreWidget() {
    // 如果还有数据
    if(this.hasMore){
      return Center(
        child: Padding(
          padding: EdgeInsets.all(10.0),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Text(
                '加载中',
                style: TextStyle(fontSize: 16.0),
              ),
              // 加载图标
              CircularProgressIndicator(
                strokeWidth: 1.0,
              )
            ],
          ),
        ),
      );
    }else{
      return Center(
        child: Text("...到底咯..."),
      );
    }
  }

  @override
  Widget build(BuildContext context) {

    return Container(
      child: Scaffold(
        body: this.datas.length==0?this._getMoreWidget():RefreshIndicator(
          onRefresh: onRefresh,
          child: ListView.builder(
              controller: scrollController,
            itemCount: datas.length,
            itemBuilder: (BuildContext context, int index){
              return Card(
                color: Colors.grey[250],
                elevation: 5.0,
                child: Builder(
                  builder: (context)=>InkWell(
                    child: new Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        SizedBox(height: 13,),
                        Padding(
                          padding: const EdgeInsets.all(10.0),
                          child: Text(
                            datas[index].title.toString(),
                            style: TextStyle(
                              fontSize: 16.0,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                        Row(
                          children: [
                            SizedBox(width: 7,),
                            SizedBox(
                              width: 340,
                              height: 200,
                              child:  CachedNetworkImage(
                                imageUrl: (datas[index].picUrl.toString() == '' ? 'https://img2.baidu.com/it/u=2997756714,2254564028&fm=253&fmt=auto&app=138&f=JPEG?w=600&h=400'
                                    :datas[index].picUrl.toString()),
                                placeholder: (context, url) =>
                                    LinearProgressIndicator(),
                              ),
                            ),
                            // Image.network(datas[index].picUrl as String,width: 335,height: 160,
                            // ),
                          ],
                        ),
                        SizedBox(height: 12,),
                        SizedBox(height: 20,),
                      ],
                    ),
                    onTap: ()=>Navigator.of(context).push(MaterialPageRoute(
                        builder: (context) => newsDetail(
                            url: datas[index].url.toString(),
                            title: datas[index].title.toString())
                    )),
                  ),
                ),
              );
            }
        ),
        )
      )
    );
  }
  String Checkurl(String url) {
    if (url.startsWith("http")) {
      return url;
    } else {
      return "http:" + url;
    }
  }
}